import socket
import Cerveau
import threading
import socketserver
import Securite
import builtins
import hashlib
import Database
import datetime

clef="florent"

class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
    def sendMsg(self,type,message):
        t=str(message)
        d=Securite.vigenere(t,clef,"1")	
        m=bytes(d,'utf-8')
        self.request.sendall(bytes(type+";",'utf-8')+bytes(d,'utf-8'))

    def handle(self):
        logFile=open("logs","a")
        builtins.sendHandler=self
        builtins.init=1
        essai=0
        identify=0
        while essai < 3:
            rec = self.request.recv(1024).strip()
            if len(rec)>0:
                clair = Securite.vigenere(rec[2:].decode(),clef,"2")
                r = clair.split(";,;")
                password=r[1]	
                username=r[0]
                mp=Database.searchUser(username).strip()
                if mp=="invalide":
                    self.sendMsg("L","identify=0")
                    essai=essai+1
                else:					
                    if hashlib.sha224(password.encode('utf-8')).hexdigest()==mp:
                        identify=1
                        self.sendMsg("L","identify=1")
                        logFile.write(username+";"+datetime.datetime.now().isoformat())
                        break
                    else:
                        self.sendMsg("L","identify=0")
                        essai=essai+1
            else:
                builtins.init=0
                print("client deconnecte")
                break

        while 1 and identify == 1:
            d = self.request.recv(1024).strip()
            if len(d)>0:
                t=d.decode()
                temp=t.split(";")
                type=temp[0]
                if type == "T":
                    data = Securite.vigenere(temp[1],clef,"2")
                    data = data.encode('iso-8859-1').decode()
                    cur_thread = threading.current_thread()
                    type,answer=Cerveau.analyse(data,username)
                    if username =="florent":
                        answer+=" (from"+str(cur_thread.name)+")"
                    self.sendMsg(type,answer)
                elif type == "F":
                    filename=temp[1]
                    file=open(filename,"wb")
                    file.write(bytes(temp[2]))
                    file.close()
            else:
                essai=0
                identify=0
                builtins.init=0
                print("client deconnecte")
                Cerveau.cleanHistory()
                break

class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    pass
